package transactions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import tables.Acces;
import tables.Sortie;
/**
 * Cette classe correspond a une transaction qui realise un sortie normal
 *
 */
public class PassageNormalSortie implements Transaction_SUPER{
	
	private Connection conn;
	//attributs ACCES
	private int numAcces;
	private int id_personne;
	//Attributs ENTREE
	private String code_batiment;
	private int codePointAcces;
	private String etat_entree;
	private Statement stat;
	
	public PassageNormalSortie(Connection conn, int id_personne,
			String code_batiment, int codePointAcces, String etat_entree) throws SQLException {
		this.conn = conn;
		this.id_personne = id_personne;
		this.code_batiment = code_batiment;
		this.codePointAcces = codePointAcces;
		this.etat_entree = etat_entree;
		this.stat = conn.createStatement();
	}


	@Override
	public void query() throws SQLException {
		try {
			conn.setAutoCommit(false);
			conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			
			//creer acces
			String cmd = new Acces(numAcces, id_personne).insert();
			stat.executeQuery(cmd);
			
			
			//recup numAcces
			String cmd1 = "SELECT SEQ_ACCES.currval FROM dual";
			ResultSet res = stat.executeQuery(cmd1);
			res.next();
			numAcces = res.getInt(1);
			
			//creer sortie
			String cmd2 = new Sortie(numAcces, code_batiment, codePointAcces, etat_entree, null).insert();
			stat.executeQuery(cmd2);
			
			conn.commit();
		} catch (SQLException e) {
			if(e.getErrorCode()==20002){
				traitementError(numAcces);
				conn.commit();
			}
			conn.rollback();
			e.printStackTrace();
		}
	}

	private void traitementError(int numAcces) throws SQLException{
		String cmd1 = new Sortie(numAcces, code_batiment, codePointAcces, "DISABLE", null).insert();
		stat.executeQuery(cmd1);
	}
}
